import { FC, useMemo, useRef } from "react";
import styles from "./StatHeader.module.scss";
import {
  Button,
  Input,
  InputRef,
  message,
  Popover,
  Space,
  Tooltip,
  Typography,
} from "antd";
import { CopyOutlined, LeftOutlined, QrcodeOutlined } from "@ant-design/icons";
import { useNavigate, useParams } from "react-router-dom";
import useGetPageInfo from "@/hooks/useGetPageInfo";
import { QRCodeSVG } from "qrcode.react";

const { Title } = Typography;

const StatHeader: FC = () => {
  const nav = useNavigate();
  const { id } = useParams();
  const { title, isPublished } = useGetPageInfo();

  const urlInputRef = useRef<InputRef>(null);
  const copy = (url: string) => {
    const elem = urlInputRef.current;
    if (elem == null) return;
    elem.select();
    navigator.clipboard.writeText(url).then(() => {
      message.success("拷贝成功");
    });
  };

  const linkAndQRCodeElem = useMemo(() => {
    if (!isPublished) return null;

    const url = `http://localhost:3000/question/${id}`; // url 参考 C 端规则

    const QRCodeElem = (
      <div style={{ textAlign: "center" }}>
        <QRCodeSVG value={url} size={150}></QRCodeSVG>
      </div>
    );

    return (
      <Space>
        <Input value={url} ref={urlInputRef} style={{ width: "300px" }} />
        <Tooltip title="拷贝链接">
          <Button icon={<CopyOutlined />} onClick={() => copy(url)}></Button>
        </Tooltip>
        <Popover placement="bottom" content={QRCodeElem}>
          <Button icon={<QrcodeOutlined />}></Button>
        </Popover>
      </Space>
    );
  }, [id, isPublished]);

  return (
    <div className={styles["header-wrapper"]}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <Title level={5}>{title}</Title>
          </Space>
        </div>
        <div className={styles.main}>{linkAndQRCodeElem}</div>
        <div className={styles.right}>
          <Button type="primary" onClick={() => nav(`/question/edit/${id}`)}>
            编辑问卷
          </Button>
        </div>
      </div>
    </div>
  );
};

export default StatHeader;
